package com.game.gm.load;

import com.game.GMClientServer;
import com.game.gm.config.GMComm;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class GMCommLoad {
	private ConcurrentHashMap<Integer, GMComm> gmComms = new ConcurrentHashMap();
	public static GMCommLoad gMCommLoad;
	public String path = "gmConfig.xml";

	public GMCommLoad() {
		try {
			DocumentBuilder docbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			String path1 = URLDecoder.decode(GMClientServer.class.getClassLoader().getResource("").getPath(), "UTF-8");
			InputStream in = new FileInputStream(path1 + this.path);
			Document doc = docbuilder.parse(in);
			NodeList rootList = doc.getChildNodes();

			if (rootList.getLength() > 0) {
				Node rootNode = rootList.item(0);
				if (rootNode.getNodeName().equals("gmcomms")) {
					NodeList gmcomms = rootNode.getChildNodes();
					for (int i = 0; i < gmcomms.getLength(); i++) {
						Node gmComm = gmcomms.item(i);
						if (gmComm.getNodeName().equals("gmcomm")) {
							NodeList gmInfos = gmComm.getChildNodes();
							GMComm gmcomm = new GMComm();
							for (int j = 0; j < gmInfos.getLength(); j++) {
								Node gmInfo = gmInfos.item(j);
								if (gmInfo.getNodeName().equals("gmName"))
									gmcomm.setGmName(gmInfo.getTextContent());
								else if (gmInfo.getNodeName().equals("comm"))
									gmcomm.setGmComm(gmInfo.getTextContent());
								else if (gmInfo.getNodeName().equals("tag")) {
									gmcomm.setTag(Integer.parseInt(gmInfo.getTextContent()));
								}
							}
							getGmComms().put(Integer.valueOf(gmcomm.getTag()), gmcomm);
						}
					}
				}
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "加载gm指令配置出错" + e.getMessage());
		}
	}

	public static GMCommLoad getInstance() {
		if (gMCommLoad == null) {
			gMCommLoad = new GMCommLoad();
		}
		return gMCommLoad;
	}

	public ConcurrentHashMap<Integer, GMComm> getGmComms() {
		return this.gmComms;
	}

	public void setGmComms(ConcurrentHashMap<Integer, GMComm> gmComms) {
		this.gmComms = gmComms;
	}
}